package com.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.beans.Movie;
import com.beans.Person;
import com.bussiness.MovieBussinessProxy;
import com.bussiness.PersonBussinessProxy;
import com.constants.ServiceEndPoints;
import com.constants.UIMessages;
import com.exceptions.MovieAlreadyIssuedException;
import com.exceptions.MovieNotExistsException;
import com.exceptions.MovieUnavailableException;
import com.exceptions.UserNotEligibleException;

/**
 * Servlet implementation class DeleteCheckoutServlet
 */
public class DeleteCheckoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	MovieBussinessProxy movieBI = new MovieBussinessProxy(); 
	PersonBussinessProxy personBI = new PersonBussinessProxy();
	Movie[] movieList;
	Movie[] billMovie;
	Movie[] Pmovies;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteCheckoutServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{
			HttpSession session = request.getSession(true);
			RequestDispatcher dispatcher;
			movieBI.setEndpoint(ServiceEndPoints.MovieEndPoint);
			personBI.setEndpoint(ServiceEndPoints.PersonEndPoint);
			String click = request.getParameter("submit");
			String[] id=request.getParameterValues("movieid");
			long userid = (Long) session.getAttribute("MembershipId");
			
			if(click.equals("Delete")){
				for(int j=0;j<id.length;j++){
					int movieid = Integer.parseInt(id[j]);
					System.out.println("movie id"+movieid);
					int status = personBI.removefromQueue(movieid, userid);
					System.out.println("status"+status);
				}
				request.setAttribute("ServerMessage","Deleted successfully from Queue");
				dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
				dispatcher.forward(request, response);
				return;
				
			}
			if(click.equals("Check Out")){
				movieList = (Movie[])session.getAttribute("cartMovies");
				billMovie = new Movie[id.length];
				int l =0;
				String type = (String) session.getAttribute("CustomerType");
				for(int j=0;j<id.length;j++){
					int movieid = Integer.parseInt(id[j]);
					for(int i=0;i<movieList.length;i++){
						if(movieList[i].getMovieId() == movieid){
							Movie movie = new Movie();
							movie.setMovieId(movieid);
							movie.setMovieName(movieList[i].getMovieName());
							movie.setMovieBanner(movieList[i].getMovieBanner());
							movie.setCategoryid(movieList[i].getCategoryid());
							movie.setTotalCopy(movieList[i].getTotalCopy());
							movie.setAvailableCopy(movieList[i].getAvailableCopy());
							movie.setRent(movieList[i].getRent());
							movie.setReleaseDate(movieList[i].getReleaseDate());
							movie.setRating(movieList[i].getRating());
							movie.setNo_of_ratings(movieList[i].getNo_of_ratings());
							billMovie[l] = movie;
							l++;
						}
					}
										
				}
				System.out.println("bill movie length:"+billMovie.length);
				int status = movieBI.isUserEligible(userid, id.length);
				System.out.println("status is user eligible "+status);
				
				if(status == 0){
					request.setAttribute("ServerMessage", "Sorry... You have crossed your rent limit.");
					dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
					dispatcher.forward(request, response);
					return;
				}
				for(int k=0;k<id.length;k++){
					System.out.println("movie id:"+Integer.parseInt(id[k]));
					int status1 = movieBI.isMovieAvailable(Integer.parseInt(id[k]));
					System.out.println("status"+status1);
					if(status1 == 0){
						request.setAttribute("ServerMessage", "Movie is not available");
						dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
						dispatcher.forward(request, response);
						return;
					}
				}
				if(type.equals("S")){
					System.out.println("Before GenerateBillSimple...");
					Double amount = movieBI.generateBillSimple(userid,billMovie);
					System.out.println("Amount :"+amount);
					session.setAttribute("billAmountSimple", amount);
					session.setAttribute("billMovies", billMovie);
					request.setAttribute("ServerMessage", "Thank you for renting Movies.Here is your bill for current month");
					dispatcher = getServletContext().getRequestDispatcher("/simplebill.jsp");
					dispatcher.forward(request, response);
					return;
				}
				if(type.equals("P")){
					System.out.println("Before GenerateBillPremium");
					Pmovies = movieBI.generateBillPremium(userid);
					//System.out.println("premium movies in that month"+ Pmovies.length);
					for(int m=0;m<billMovie.length;m++){
						movieBI.issueMovie(billMovie[m].getMovieId(), userid);
					}
					request.setAttribute("ServerMessage", "Thank you for renting Movies.Here is your bill for current month");
					session.setAttribute("billMovies", billMovie);
					session.setAttribute("premiumMovies", Pmovies);
					dispatcher = getServletContext().getRequestDispatcher("/premiumbill.jsp");
					dispatcher.forward(request, response);
					return;
				}
										
			}
		
				
			
		}catch(MovieAlreadyIssuedException m){
			request.setAttribute("ServerMessage", "Movie already Issued to you");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
			dispatcher.forward(request, response);
		}
		catch(MovieUnavailableException mu){
			request.setAttribute("ServerMessage", "Movie is not available");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
			dispatcher.forward(request, response);
		}
		catch(UserNotEligibleException u){
			request.setAttribute("ServerMessage", "Sorry... You have crossed your rent limit.");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
			dispatcher.forward(request, response);
		}
		catch(MovieNotExistsException n){
			request.setAttribute("ServerMessage", "Movie not exist...");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
			dispatcher.forward(request, response);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			request.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/cartDetails.jsp");
			dispatcher.forward(request, response);
			
		}
	}

}	


